const conn = require('../db/index.js')

// 获取品牌列表
const brandList = (req, res) => {
  const output={
    code:200,
    msg:'ok'
  }
  const sql=`select * from brand order by id desc`
  conn.query(sql, (err, result) => {
    if(err){
      return console.log('错误信息:',err.message)
    }
    output.list=result
    res.send(output)
  })
}

// 添加品牌
const brandAdd = (req, res) => {
  const output={
    code:200,
    msg:'ok'
  }
  const ctime=Date.now()
  const name=req.body.name
  
  const sql=`insert into brand set name=?,ctime=${ctime}`
  conn.query(sql,[name],(err, result) => {
    if(err){
      output.code=1
      return console.log('错误信息:',err.message)
    }
    output['id']=result['insertId']
    res.send(output)
  })
}
// 删除品牌

const brandDel = (req, res) => {
  const output={
    code:200,
    msg:'ok'
  }
  const id=req.params.id
  if(id==''){
    output.code=1
    output.msg='参数错误'
    return
  }
  const sql=`delete from brand where id=?`
  conn.query(sql,[id], (err, result) => {
    if(err){
      output.code=2
      return console.log('错误信息:',err.message)
    }
    res.send(output)
  })
}


// 品牌详情
const brandDetail = (req, res) => {
  const output={
    code:200,
    msg:'ok'
  }
  const id=req.params.id
  if(id==''){
    output.code=1
    output.msg='参数错误'
    return
  }
  const sql=`select * from brand where id=?`
  conn.query(sql,[id], (err, result) => {
    if(err){
      output.code=2
      return console.log('错误信息:',err.message)
    }
    output.list=result;
    res.send(output)
  })
}

// 更新品牌
const brandEdit = (req, res) => {
  const output={
    code:200,
    msg:'ok'
  }
  const id=req.params.id
  if(id==''){
    output.code=1
    output.msg='参数错误'
    return
  }
  const ctime=Date.now()
  const name=req.body.name
  const sql=`update brand set name=?,ctime=${ctime} where id=?`
  conn.query(sql,[name,id], (err, result) => {
    if(err){
      output.code=2
      return console.log('错误信息:',err.message)
    }
    res.send(output)
  })
}

module.exports = {
  brandList,
  brandAdd,
  brandDel,
  brandEdit,
  brandDetail
}
